package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.UerService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;

/**
 * @author : [chenxys]
 * @version : [v1.0]
 * @Description : 用户管理
 * @createTime : [2022/5/31 22:34]
 */
@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Reference
    private UerService uerService;

    /**
     * 获取当前登录用户的用户名
     * @author chenxys
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/getUsername")
    public Result getUsername(){
        //当Spring security完成认证后，会将当前用户信息保存到框架提供的上下文对象 这个user为Spring security提供的user
        /*
         * SecurityContextHolder:spring security 提供的类似于工具类
         * getContext():获取上下文对象
         * getAuthentication():获取登录用户的认证信息
         * getPrincipal():获取当前登录的user[框架提供的user]对象
         */
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println(user);
        //如果获取到了user对象
        if (user != null){
            //获取当前登录的用户的用户名
            String username = user.getUsername();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }
        //获取用户失败
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }

    /**
     * 根据用户名获取用户所有信息
     * @author chenxys
     * @param username 用户名
     * @return com.itheima.entity.Result
     */
    @RequestMapping(value = "/getUser")
    public Result getUser(String username){
        try {
            com.itheima.pojo.User user = uerService.findByUsername(username);
            return new Result(true,MessageConstant.GET_USER_SUCCESS,user);
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_USER_FAIL);
        }
    }
}
